package com.project.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * Created by zhangjk on 2016/1/14.
 */
@RestController
public class FileUploadController {
    private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    @Value("${file.upload.path}")
    private String rootPath;
    
	/**
     * Upload single file using Spring Controller
     */
    @RequestMapping(value = "/uploadFile/avatar", method = RequestMethod.POST, produces = "application/json;charset=utf8")
    public @ResponseBody Map<String, String> uploadFileHandler(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
    	Map<String, String> map = new HashMap<String, String>();
    	HttpSession session = request.getSession();
		if (null == session.getAttribute("userId")) {
			map.put("code", "-1");
			map.put("msg", "登录已失效，请重新登录");
			return map;
		}
        if (!file.isEmpty()) {
            InputStream in = null;
            OutputStream out = null;
            File dir = null;
            String fileName = null;
            String suffixName = null;

            try {
            	////根目录》功能目录》日期目录》文件名[会员ID+时间戳]
            	String funName = "/member/"+session.getAttribute("userId");
            	
                dir = new File(rootPath + funName);
                
                if (!dir.exists())
                    dir.mkdirs();
                fileName = session.getAttribute("userId") + "_" + System.currentTimeMillis();
                suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                File serverFile = new File(dir.getAbsolutePath() + File.separator + fileName + "." + suffixName);
                in = file.getInputStream();
                out = new FileOutputStream(serverFile);
                byte[] b = new byte[1024];
                int len = 0;
                while ((len = in.read(b)) > 0) {
                    out.write(b, 0, len);
                }
                out.close();
                in.close();
                logger.info("Server File Location=" + serverFile.getAbsolutePath());

                map.put("name", file.getOriginalFilename());
                map.put("url", funName + File.separator + fileName + "." + suffixName);
                map.put("msg", "上传成功");
                map.put("code", "1");
                return map;

            } catch (Exception e) {
                map.put("name", file.getOriginalFilename());
                map.put("url", dir.getAbsolutePath() + File.separator + fileName + "." + suffixName);
                map.put("msg", "上传失败");
                map.put("code", "0");
                return map;
            } finally {
                if (out != null) {
                    out.close();
                    out = null;
                }
                if (in != null) {
                    in.close();
                    in = null;
                }
            }
        } else {
            map.put("name", file.getOriginalFilename());
            map.put("url", "uploadFiles" + File.separator + file.getOriginalFilename());
            map.put("msg", "上传失败");
            map.put("code", "0");
            return map;
        }
    }
}
